<!-- 层级奖励配置 -->
<template>
    <div >
        <div class='table-page-search-wrapper'>
            <a-form layout='inline'>
               <a-row :gutter='48'>
                    <a-col :md='16' :sm='24'>
                    </a-col>
                    <a-col :md="8" :sm="24">
                        <a-form-item >
                            <span>总开关：</span>
                            <a-switch checked-children="开" un-checked-children="关" :checked="allItem.onOff == 1 ? true : false" @change="changeAllOnOff"/>
                            <!-- <a-button style="margin-left: 20px" type="primary" @click="getAllData()">查询</a-button> -->
                            <!-- <a-button style="margin-left: 20px" type="primary" icon="plus" @click="add()">新增</a-button> -->
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </div>  

        <!-- 表格 -->
        <a-tabs v-model="moduleClassificationId" @change="changeClassification">
            <a-tab-pane v-for="(item) in moduleClassificationList" :key="item.id" :tab="item.name">
                <a-table rowKey="id" :loading="isload" :columns="columns" :data-source="dataList"  size="small" >
                    <div slot="grade" slot-scope="grade">
                        <div v-for="(item,i) in gradeList" :key="item.id">
                            <a-tag v-if="item.grade == grade" :color="colors[i]">{{item.gradeName}}</a-tag>
                        </div>
                    </div>
                    <div v-for="(item) in levelList" :key="item.id" :slot="`level${item.id}`" slot-scope="text,record">
                        <div @click="update(record[`level${item.id}`])">
                            <div v-if="record[`level${item.id}`].onOff == '1'">奖励：{{record[`level${item.id}`].isPercent == '1' ? (record[`level${item.id}`].awardNumber * 100).toFixed(3) : record[`level${item.id}`].awardNumber }}{{record[`level${item.id}`].isPercent == '1' ? '%' : '元'}}</div>
                            <div v-else>奖励：0.00%</div>
                        </div>
                    </div>
                </a-table>
            </a-tab-pane>
        </a-tabs>

        <a-modal
            title="添加、修改层级奖励数量配置"
            :visible="visible"
            :confirm-loading="confirmLoading"
            @ok="handleOk"
            @cancel="visible = false"
            >
            <div>
                <a-form :label-col="{ span: 8 }" :wrapper-col="{ span: 15 }">
                    <a-form-item label="等级">
                        <a-select v-model="item.grade" placeholder="请选择" disabled allowClear>
                            <a-select-option v-for="(item,i) in gradeList" :key="i" :value="item.grade">{{item.gradeName}}</a-select-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="层级">
                        <a-select v-model="item.level" disabled placeholder="请选择" allowClear>
                            <a-select-option v-for="(item,i) in levelList" :key="i" :value="item.id">{{item.name}}</a-select-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="奖励数量">
                        <a-input v-model="item.awardNumber" placeholder="请输入奖励数量" allow-clear :suffix="item.isPercent == 1 ? '%' : ''"></a-input>
                    </a-form-item>
                    <a-form-item label="是否按比例发放奖励">
                        <a-radio-group v-model="item.isPercent" >
                            <a-radio :value="1">是</a-radio>
                            <a-radio :value="0">否</a-radio>
                        </a-radio-group>
                    </a-form-item>
                    <a-form-item label="是否开启">
                        <a-radio-group v-model="item.onOff" >
                            <a-radio  v-for="(item,i) in statusList" :key="i" :value="item.id">{{item.name}}</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-form>
            </div>
        </a-modal>
    </div>
</template>

<script>
import { queryAwardModelNumberConfig , updateAwardModelNumberConfig , queryGradeProduct } from '@/api/product';
export default {
    data () {
        return {
            brandId: this.global.brandId,
            gradeList: [],
            isload: false,
            dataList: [],
            activeKey: 1,
            moduleClassificationList: [
                // { id: 15, name: '返利'},
                // { id: 10, name: '购买商品'},
                // { id: 3, name: '话费快充'},
                // { id: 7, name: '话费慢充'},
                // { id: 4, name: '会员权益'},
                { id: 16, name: '分享朋友圈奖励'},
            ],
            accountType: '0',
            accountTypeList: [
                { id: 0, name: 'CNY'},
                // { id: 6, name: '能量水晶'},
            ],
            moduleClassificationId: 16,
            statusList: [
                { id: 1, name: '开启'},
                { id: 0, name: '关闭'},
            ],
            level: undefined,
            levelList: [
                { id: '0', name: '自己'},
                // { id: '1', name: '直推'},
                // { id: '2', name: '间推'},
                // { id: '3', name: '间间推'},
            ],
            columns: [],
            colors: ['blue','purple','cyan','green','orange','red','pink','brown','indigo','lime','purple','teal','yellow','amber'],
            allItem : {
                id: '',
                awardModel: '', // 奖励类型  0：全局开关，1：大数据，2：信用卡，3：话费充值，4：会员权益
                accountType: '0', // 帐户类型，0：CNY，6：能量水晶
                level: '', // 层级，1：直推，2：间推
                grade: undefined, // 等级
                awardNumber: '', // 奖励数量
                onOff: '1', // 状态(0:下架,1:上架)
                isPercent: '0', // 是否按比例发放奖励
            },
            visible: false,
            confirmLoading: false,
            item: {
                id: '',
                awardModel: '', // 奖励类型  0：全局开关，1：大数据，2：信用卡，3：话费充值，4：会员权益
                accountType: '0', // 帐户类型，0：CNY，6：能量水晶
                level: '', // 层级，1：直推，2：间推
                grade: undefined, // 等级
                awardNumber: '', // 奖励数量
                onOff: 1, // 状态(0:下架,1:上架)
                isPercent: 0, // 是否按比例发放奖励
            },
        };
    },
    async created(){
        try {
            // await this.getBrand()
            this.gradeList = await this.getGrade(this.brandId)
            this.sortOutColumns();
            this.getData(0)
            this.getData()
        } catch (error) {
            this.$notification['error']({
                message: '提示',
                description: '网路丢失，请稍后再试！',
                duration: 8,
            })
        }
    },
    methods: {
        // 查询等级信息
        getGrade(brandId){
            let _this = this
            return new Promise((resolve,reject)=>{
                const params = {
                    'brandId':brandId,
                    'size':99,
                    'page':0,
                }
                queryGradeProduct(params)
                .then(res=>{
                    if(res.success){
                        resolve(res.data.content)
                    }else{
                        reject()
                    }
                })
            })
        },
        // 查询产品详情信息配置
        getData(awardModel){
            var _this = this
            _this.isload = true
            const params = {
                brandId: _this.brandId,
                awardModel: awardModel === 0 ? awardModel : _this.moduleClassificationId,
                accountType:_this.accountType,
                level: _this.level,
                onOff:_this.status,
                // page: _this.page - 1,
                // size: _this.size,
                page: 0,
                size: 99,
            }
            queryAwardModelNumberConfig(params)
            .then(res=>{
                if(res.success){
                    if(awardModel === 0 && res.data.content.length > 0){
                        _this.allItem = JSON.parse(JSON.stringify(res.data.content[0]));
                    }else{
                        // _this.dataList = res.data.content
                        // _this.total = res.data.totalElements
                        _this.sortOutData(res.data.content)
                        // 处理数据
                    }
                    _this.isload = false
                    console.log(_this.dataList,'dataList')
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 切换tab
        async changeClassification(key){
            this.isload = true
            this.activeKey = key
            setTimeout(()=>{
                this.getData();
            },500)
        },
        // 整理表格
        sortOutColumns(){
            let _this = this;
            var columns = [];
            columns.push({
                'title': '等级',
                'dataIndex': 'grade',
                'key': 'grade',
                'scopedSlots': { customRender: 'grade' },
                'align': 'center',
            })
            for (let index = 0; index < _this.levelList.length; index++) {
                const levels = _this.levelList[index];
                columns.push({
                    'title': levels.name,
                    'dataIndex': `level${levels.id}`,
                    'key': `level${levels.id}`,
                    'scopedSlots': { customRender: `level${levels.id}` },
                    'align': 'center',
                })
            }
            _this.columns = columns;
        },
        // 整理数据
        sortOutData(list){
            let _this = this;
            var arr = [];
            for (let index = 0; index < _this.gradeList.length; index++) {
                const gradeItem = _this.gradeList[index];
                let gradeObj = {
                    'grade': gradeItem.grade,
                };
                for (let j = 0; j < _this.levelList.length; j++) {
                    const levelItem = _this.levelList[j];
                    // gradeObj[`level${levelItem.id}`] = 
                    var item = list.find(item => item.grade == gradeItem.grade && item.level == levelItem.id);
                    if(item){
                        gradeObj[`level${levelItem.id}`] = item;
                    }else{
                        gradeObj[`level${levelItem.id}`] = {
                            'id': '',
                            'level': levelItem.id,
                            'awardModel': _this.moduleClassificationId,
                            'awardNumber': 0,
                            'isPercent': 1,
                            'onOff': 1,
                            'grade': gradeItem.grade,
                            'accountType': '0',
                        }
                    }
                }
                arr.push(gradeObj);
            }
            _this.dataList = arr;
            console.log(arr,'arr');
        },
        // sortOutData(list){
        //     let _this = this;
        //     var arr = [];
        //     for (let index = 0; index < _this.gradeList.length; index++) {
        //         const gradeItem = _this.gradeList[index];
        //         var levels = [];
        //         for (let j = 0; j < _this.levelList.length; j++) {
        //             const levelItem = _this.levelList[j];
        //             if(list.find(item => item.grade == gradeItem.grade && item.level == levelItem.id)){
        //                 levels.push(list.find(item => item.grade == gradeItem.grade && item.level == levelItem.id))
        //             }else{
        //                 levels.push({
        //                     'id': '',
        //                     'level': levelItem.id,
        //                     'awardModel': _this.moduleClassificationId,
        //                     'awardNumber': 0,
        //                     'isPercent': '1',
        //                     'onOff': '1',
        //                     'grade': gradeItem.grade,
        //                     'accountType': '0',
        //                 })
        //             }
        //         }
        //         arr.push(levels);
        //     }
        //     _this.dataList = arr;
        //     console.log(arr,'处理后的数据');
        // },
        // 修改总开关状态
        changeAllOnOff(){
            console.log(this.allItem)
            if(this.allItem.id == ''){
                return;
            }
            let _this = this
            const params = {
                // 'id':_this.allItem.id,
                'brandId':_this.allItem.brandId,
                'awardModel':_this.allItem.awardModel,
                'accountType':_this.allItem.accountType,
                'level':_this.allItem.level,
                'awardNumber':_this.allItem.awardNumber,
                'onOff':_this.allItem.onOff == 1 ? 0 : 1,
                'isPercent': _this.allItem.isPercent,
            }
            updateAwardModelNumberConfig(params)
            .then(res=>{
                _this.confirmLoading = false
                if(res.success){
                    _this.$notification['success']({
                        message: '提示',
                        description: '修改成功',
                        duration: 8,
                    })
                    _this.visible = false
                    _this.getData(0)
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 修改
        async update(record) {
            this.item = JSON.parse(JSON.stringify(record))
            console.log(this.item,'item')
            if(record.isPercent == 1){
                this.item.awardNumber = record.awardNumber * 100
            }
            this.visible = true
        },
        // 确定添加、修改轮播图
        handleOk(){
            console.log(this.item,'itm')
            console.log(this.fileList,'filelist')
            var _this = this
            if(_this.item.accountType === undefined){
                this.$message.warning('请选择奖励类型');
                return
            }
            if(_this.item.level === undefined){
                this.$message.warning('请选择层级');
                return
            }
            if(_this.item.awardNumber === ''){
                this.$message.warning('请输入奖励数量');
                return
            }
            const params = {
                'brandId': _this.brandId,
                // 'id': _this.item.id,
                'awardModel': _this.item.awardModel,
                'accountType': _this.item.accountType,
                'level': _this.item.level,
                'isPercent': _this.item.isPercent,
                'grade': _this.item.grade,
                'onOff': _this.item.onOff,
                'awardNumber': _this.item.isPercent == 1 ? (_this.item.awardNumber / 100) : _this.item.awardNumber,
            }
            updateAwardModelNumberConfig(params)
            .then(res=>{
                if(res.success){
                    _this.$notification['success']({
                        message: '提示',
                        description: _this.item.id ? '修改成功' : '添加成功',
                        duration: 8,
                    })
                    _this.visible = false
                    _this.getData()
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
    }
}

</script>
<style scoped>

</style>